package net.xyuu;

import static org.junit.Assert.fail;

import java.io.File;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import org.hibernate.HibernateException;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaValidator;
import org.hibernate.tool.schema.spi.SchemaManagementTool;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class TargetTableGenerator {

	private Metadata metadata;

	private ServiceRegistry serviceRegistry;

	private SessionFactoryImplementor sf;

	@PersistenceUnit
	private EntityManagerFactory entityManagerFactory;

	@Before
	public void setup() throws Exception {

		sf = entityManagerFactory.unwrap(SessionFactoryImplementor.class);
		serviceRegistry = sf.getServiceRegistry();

		File file = new File("D:/Code/workspace/platform/src/test/resources/net/xyuu/item.hbm.xml");
		ServiceRegistry ssr = serviceRegistry.getParentServiceRegistry();
		MetadataSources metadataSources = new MetadataSources(ssr);
		metadataSources.addFile(file);
		metadata = metadataSources.getMetadataBuilder().applyPhysicalNamingStrategy(new SpringPhysicalNamingStrategy())
				.build();
	}

	@Test
	public void testTableGenerator() throws Exception {
		final Map settings = serviceRegistry.getService(ConfigurationService.class).getSettings();

		final SchemaManagementTool tool = serviceRegistry.getService(SchemaManagementTool.class);
		tool.getSchemaDropper(settings).doDrop(metadata, false);
		tool.getSchemaCreator(settings).doCreation(metadata, false);
		try {
			new SchemaValidator(serviceRegistry, (MetadataImplementor) metadata).validate();
		} catch (HibernateException e) {
			fail("The identifier generator table should have validated.  " + e.getMessage());
		} finally {
			tool.getSchemaDropper(settings).doDrop(metadata, false);
		}
	}

}
